package cn.ticsmyc.tools.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Ticsmyc
 * @date 2020-12-21 21:40
 */
public class TicAopHandler implements InvocationHandler,net.sf.cglib.proxy.InvocationHandler {

    //增强对象
    private Object target;
    //增强方法
    private EnhancementAdvice advice;


    public TicAopHandler(Object target, EnhancementAdvice advice){
        this.target = target;
        this.advice = advice;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        //跳过Object方法
        if(Object.class.equals(method.getDeclaringClass())){
            return method.invoke(this,args);
        }
        //开始aop逻辑
        EnhanceInfo enhanceInfo = new EnhanceInfo(proxy,method,args);

        if(advice.preInvoke(enhanceInfo)){
            //前置处理返回true时，后续方法不再执行
            return enhanceInfo.getResult();
        }
        Object result=null;
        try{
            //调用真实业务方法
            System.out.println("*** 调用的方法为"+ method);
            result = method.invoke(target, args);
            enhanceInfo.setResult(result);
            //执行postInvode增强
            advice.postInvoke(enhanceInfo);
            return enhanceInfo.getResult();
        }catch(Exception e){
            enhanceInfo.setException(e);
            //抛出异常时的增强
            advice.postThrowing(enhanceInfo);
            return enhanceInfo.getResult();
        }finally {
            //无论如何都要执行结果返回
            advice.postReturning(enhanceInfo);
        }
    }
}
